﻿
#region Using Statements
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
using Microsoft.Xna.Framework.Media;
using _0812367_0912581;
using Microsoft.Xna.Framework.Audio;
using GameStateManagement.Mine;
using GameStateManagement.GameHelper;

namespace GameStateManagement
{
    
    class GameplayScreen : GameScreen
    {
        #region Fields

        ContentManager content;
        SpriteFont gameFont;

        Vector2 playerPosition = new Vector2(100, 100);
        Vector2 enemyPosition = new Vector2(100, 100);

        Song background_sound;
        Random random = new Random();

        float pauseAlpha;
        private Texture2D Background;


        


        KeyboardState keyboardState;
        KeyboardState oldKeyboardState;

        //GameScreen
        MyGameScreen currentScreen;//****
        GameMenuScreen gameMenuScreen;
        ActionScreen actionScreen;
        PopUpScreen quitScreen;
        PopUpScreen changeLevleScreen;
        PopUpScreen saveGame;
        PopUpScreen loadGame;
        PopUpScreen settingGame;
        OtherScreen winGameScreen;
        OtherScreen gameOverScreen;
        OtherScreen aboutScreen;


        GamePadState gamePadState;
        GamePadState oldGamePadState;


        SoundEffect mainScreenSound;
        SoundEffectInstance instanceSound;

        #endregion


        public int StartupLevel { get; set; }

        #region Initialization


        
        
        
        public GameplayScreen()
        {
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
            currentScreen = actionScreen;
            ActionScreen.screenSate = (int)ActionScreen.ScreenState.InGame;

        }


        
        
        
        public override void LoadContent()
        {
            if (content == null)
                content = new ContentManager(ScreenManager.Game.Services, "Content");

            //gameFont = content.Load<SpriteFont>("gamefont");

            //Background = content.Load<Texture2D>("pvsz");

            
            
            
            //Thread.Sleep(1000);

            //background_sound = content.Load<Song>("Sound\\Choose Your Seeds - Laura Shigihara");
            //MediaPlayer.Play(background_sound);

            ContentManager Content = this.ScreenManager.Game.Content;
            GameComponentCollection Components =             this.ScreenManager.Game.Components;
            SpriteBatch spriteBatch = this.ScreenManager.SpriteBatch;


            gameMenuScreen = new GameMenuScreen(
                this.ScreenManager.Game,
                spriteBatch,
                Content.Load<SpriteFont>("menufont"),
                Content.Load<Texture2D>("Resources\\Background"));
            Components.Add(gameMenuScreen);
            gameMenuScreen.Hide();


            actionScreen = new ActionScreen(
        this.ScreenManager.Game,
        spriteBatch,
        Content.Load<Texture2D>("Resources\\bgr")) { CurLevel = StartupLevel };

            Components.Add(actionScreen);

            actionScreen.LoadContent();
            actionScreen.Hide();



            quitScreen = new PopUpScreen(
                this.ScreenManager.Game,
                spriteBatch,
                Content.Load<SpriteFont>("menufont"),
                Content.Load<Texture2D>("Resources\\quitscreen"));
            Components.Add(quitScreen);
            quitScreen.Hide();

            changeLevleScreen = new PopUpScreen(this.ScreenManager.Game, spriteBatch, Content.Load<SpriteFont>("menufont"),
                Content.Load<Texture2D>("Resources\\ChangeLevelScreen"));
            Components.Add(changeLevleScreen);
            changeLevleScreen.Hide();

            winGameScreen = new OtherScreen(this.ScreenManager.Game, spriteBatch, Content.Load<SpriteFont>("menufont"),
                Content.Load<Texture2D>("Resources\\WingameScreen"));
            Components.Add(winGameScreen);
            winGameScreen.Hide();

            gameOverScreen = new OtherScreen(this.ScreenManager.Game, spriteBatch, Content.Load<SpriteFont>("menufont"),
                Content.Load<Texture2D>("Resources\\GameoverScreen")) { Text = "Press Enter to back to Main Menu" };
            Components.Add(gameOverScreen);
            gameOverScreen.Hide();

            saveGame = new PopUpScreen(this.ScreenManager.Game, spriteBatch, Content.Load<SpriteFont>("menufont"),
                Content.Load<Texture2D>("Resources\\bg2"));
            Components.Add(saveGame);
            saveGame.Hide();

            loadGame = new PopUpScreen(this.ScreenManager.Game, spriteBatch, Content.Load<SpriteFont>("menufont"),
                Content.Load<Texture2D>("Resources\\bg2"));
            Components.Add(loadGame);
            loadGame.Hide();

            settingGame = new PopUpScreen(this.ScreenManager.Game, spriteBatch, Content.Load<SpriteFont>("menufont"),
                Content.Load<Texture2D>("Resources\\bg2"));
            Components.Add(settingGame);
            settingGame.Hide();


            aboutScreen = new OtherScreen(this.ScreenManager.Game, spriteBatch, Content.Load<SpriteFont>("menufont"),
                Content.Load<Texture2D>("Resources\\bg2"));
            Components.Add(aboutScreen);
            aboutScreen.Hide();


            //activeScreen = startScreen;
            currentScreen = actionScreen;
            currentScreen.Show();

            mainScreenSound = Content.Load<SoundEffect>("Sound\\Audio");
            instanceSound = mainScreenSound.CreateInstance();
            this.ScreenManager.Game.IsMouseVisible = true;
            // once the load has finished, we use ResetElapsedTime to tell the game's
            // timing mechanism that we have just finished a very long frame, and that
            // it should not try to catch up.
            ScreenManager.Game.ResetElapsedTime();
        }


        
        
        
        public override void UnloadContent()
        {
          

            MediaPlayer.Stop();
            content.Unload();
            instanceSound.Stop();
            instanceSound.Dispose();
            // Xóa các screen đã tạo trong gameplay screen
            GameComponentCollection Components = this.ScreenManager.Game.Components;
            while (Components.Count > 1)
            {
                if (Components[Components.Count - 1].Equals(this.ScreenManager))
                    break;
                Components.RemoveAt(Components.Count - 1);
            }
            this.ScreenManager.Game.IsMouseVisible = false;
        }


        #endregion

        

        #region Update and Draw


        void SaveLevel()
        {
            if (GameSettings.Instance.AutoSave)
            {
                GameSettings.Instance.LastLevel = actionScreen.CurLevel;
            }
            else
            {
                GameSettings.Instance.LastLevel = -1;
            }
            GameSettings.Instance.Save();
        }
        
        
        
        
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {


            keyboardState = Keyboard.GetState();
            gamePadState = GamePad.GetState(PlayerIndex.One);
            if (currentScreen == gameMenuScreen)
            {
                HandleGameMenuScreen();
                if (instanceSound.State == SoundState.Stopped)
                {
                    instanceSound.Play();
                    //instanceSound.IsLooped = true;
                }
            }
            else//Khong phai man hinh chinh
            {
                instanceSound.Stop();
                if (currentScreen == actionScreen)
                {
                    HandleActionScreen();
                }
                else
                    if (currentScreen == quitScreen)
                    {
                        SaveLevel();
                        HandleQuitScreen();
                    }
                    else
                        if (currentScreen == changeLevleScreen)
                        {
                            HandleChanglevelScreen();
                        }
                        else
                            if (currentScreen == winGameScreen)
                            {
                                SaveLevel();
                                HandleWinGameScreen();
                            }
                            else
                                if (currentScreen == gameOverScreen)
                                {
                                    SaveLevel();
                                    HandleGameoverScreen();
                                }              
            }

            //currentScreen.Update(gameTime);

            
            oldKeyboardState = keyboardState;
            oldGamePadState = gamePadState;


            base.Update(gameTime, otherScreenHasFocus, false);

            
            //if (coveredByOtherScreen)
            //    pauseAlpha = Math.Min(pauseAlpha + 1f / 32, 1);
            //else
            //    pauseAlpha = Math.Max(pauseAlpha - 1f / 32, 0);

            //if (IsActive)
            //{
            //    // Apply some random jitter to make the enemy move around.
            //    const float randomization = 10;

            //    enemyPosition.X += (float)(random.NextDouble() - 0.5) * randomization;
            //    enemyPosition.Y += (float)(random.NextDouble() - 0.5) * randomization;

            //    // Apply a stabilizing force to stop the enemy moving off the screen.
            //    Vector2 targetPosition = new Vector2(
            //        ScreenManager.GraphicsDevice.Viewport.Width / 2 - gameFont.MeasureString("Insert Gameplay Here").X / 2, 
            //        200);

            //    enemyPosition = Vector2.Lerp(enemyPosition, targetPosition, 0.05f);

            //    // TODO: this game isn't very fun! You could probably improve
            //    // it by inserting something more interesting in this space :-)
            //}
        }


        
        
        
        
        public override void HandleInput(InputState input)
        {
            if (input == null)
                throw new ArgumentNullException("input");

            // Look up inputs for the active player profile.
            int playerIndex = (int)ControllingPlayer.Value;

            KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];
            GamePadState gamePadState = input.CurrentGamePadStates[playerIndex];

            // The game pauses either if the user presses the pause button, or if
            // they unplug the active gamepad. This requires us to keep track of
            // whether a gamepad was ever plugged in, because we don't want to pause
            // on PC if they are playing with a keyboard and have no gamepad at all!
            bool gamePadDisconnected = !gamePadState.IsConnected &&
                                       input.GamePadWasConnected[playerIndex];

            if (input.IsPauseGame(ControllingPlayer) || gamePadDisconnected)
            {
                ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer);
            }
            else
            {
                // Otherwise move the player position.
                Vector2 movement = Vector2.Zero;

                if (keyboardState.IsKeyDown(Keys.Left))
                    movement.X--;

                if (keyboardState.IsKeyDown(Keys.Right))
                    movement.X++;

                if (keyboardState.IsKeyDown(Keys.Up))
                    movement.Y--;

                if (keyboardState.IsKeyDown(Keys.Down))
                    movement.Y++;

                Vector2 thumbstick = gamePadState.ThumbSticks.Left;

                movement.X += thumbstick.X;
                movement.Y -= thumbstick.Y;

                if (movement.Length() > 1)
                    movement.Normalize();

                playerPosition += movement * 2;
            }
        }


        
        
        
        public override void Draw(GameTime gameTime)
        {
            // This game has a blue background. Why? Because!
            ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                               Color.CornflowerBlue, 0, 0);
            
            // Our player and enemy are both actually just text strings.
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

            //Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
            //Rectangle fullscreen = new Rectangle(0, 0, viewport.Width, viewport.Height);


            //spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);            
            base.Draw(gameTime);
            //spriteBatch.End();

            //spriteBatch.Draw(Background, fullscreen, Color.White);

            

            //spriteBatch.DrawString(gameFont, "Killer...................",
            //                       enemyPosition, Color.DarkRed);

            //spriteBatch.End();

            
            //if (TransitionPosition > 0 || pauseAlpha > 0)
            //{
            //    float alpha = MathHelper.Lerp(1f - TransitionAlpha, 1f, pauseAlpha / 2);

            //    ScreenManager.FadeBackBufferToBlack(alpha);
            //}
        }



        public bool CheckButton(Buttons button)
        {
            return gamePadState.IsButtonUp(button) &&
                oldGamePadState.IsButtonDown(button);
        }

        public void HandleGameMenuScreen()
        {
            if (CheckKey(Keys.Enter) || CheckButton(Buttons.A))
            {
                if (gameMenuScreen.SelectedIndex == (int)GameMenuScreen.MENUSTATE.STARTGAME)
                {
                    currentScreen.Hide();
                    currentScreen = actionScreen;
                    currentScreen.Show();
                }

                if (gameMenuScreen.SelectedIndex == (int)GameMenuScreen.MENUSTATE.EXIT)
                {
                    this.ExitScreen();
                }


            }
        }
        public void HandleActionScreen()
        {
            if (CheckKey(Keys.Escape) || CheckKey(Keys.P))
            {
                ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer);
            }
           
            if (CheckButton(Buttons.Back) || CheckKey(Keys.Q))
            {
                //currentScreen.Enabled = false;
                currentScreen.Hide();
                currentScreen = quitScreen;
                currentScreen.Show();
            }
            if (ActionScreen.screenSate == (int)ActionScreen.ScreenState.InGame)
            {
                currentScreen.Hide();
                currentScreen = actionScreen;
                currentScreen.Show();
                ActionScreen.screenSate = (int)ActionScreen.ScreenState.InGame;
            }
            if (ActionScreen.screenSate == (int)ActionScreen.ScreenState.ChangeLevel)
            {
                //currentScreen.Enabled = false;//***
                currentScreen.Hide();
                currentScreen = changeLevleScreen;
                currentScreen.Show();
            }
            else
                if (ActionScreen.screenSate == (int)ActionScreen.ScreenState.WinGame)
                {
                    currentScreen.Hide();
                    currentScreen = winGameScreen;
                    currentScreen.Show();
                }
                else
                    if (ActionScreen.screenSate == (int)ActionScreen.ScreenState.GameOver)
                    {
                        currentScreen.Hide();
                        currentScreen = gameOverScreen;
                        currentScreen.Show();
                    }

          

        }
        private void HandleQuitScreen()
        {
            if (CheckKey(Keys.Enter) || CheckButton(Buttons.A))
            {
                if (quitScreen.SelectedIndex == (int)PopUpScreen.GAMESTATE.YES)
                {
                    currentScreen.Hide();
                    currentScreen = gameMenuScreen;
                    currentScreen.Show();
                    //actionScreen.Hide();//****
                }
                else
                    if (quitScreen.SelectedIndex == (int)PopUpScreen.GAMESTATE.NO)
                    {
                        currentScreen.Hide();
                        currentScreen = actionScreen;
                        currentScreen.Show();
                    }
            }
        }

        public void HandleChanglevelScreen()
        {
            if (CheckKey(Keys.Enter) || CheckButton(Buttons.A))
            {
                if (changeLevleScreen.SelectedIndex == (int)PopUpScreen.GAMESTATE.YES)
                {
                    currentScreen.Hide();
                    currentScreen = actionScreen;
                    currentScreen.Show();
                    ActionScreen.screenSate = (int)ActionScreen.ScreenState.InGame;

                }
                else
                    if (changeLevleScreen.SelectedIndex == (int)PopUpScreen.GAMESTATE.NO)
                    {
                        currentScreen.Hide();
                        currentScreen = gameMenuScreen;
                        currentScreen.Show();
                        actionScreen.Hide();
                    }

            }
        }

        public void HandleWinGameScreen()
        {
            if (CheckKey(Keys.Enter) || CheckButton(Buttons.A))
            {
                if (winGameScreen.SelectedIndex == (int)OtherScreen.GAMESTATE.OK)
                {
                    //currentScreen.Hide();
                    //currentScreen = gameMenuScreen;
                    //currentScreen.Show();
                    //ActionScreen.screenSate = (int)ActionScreen.ScreenState.InGame;
                    //this.UnloadContent();
                    //this.ExitScreen();
                }
            }
        }

        public void HandleGameoverScreen()
        {
            if (CheckKey(Keys.Enter) || CheckButton(Buttons.A))
            {
                if (winGameScreen.SelectedIndex == (int)OtherScreen.GAMESTATE.OK)
                {
                    //currentScreen.Hide();
                    //currentScreen = gameMenuScreen;
                    //currentScreen.Show();
                    
                    //this.UnloadContent();
                    //this.ExitScreen();
                    
                    currentScreen = actionScreen;

                    ActionScreen.screenSate = (int)ActionScreen.ScreenState.InGame;
                    instanceSound.Stop();
                    LoadingScreen.Load(ScreenManager, false, null, new BackgroundScreen(),
                                                           new MyMainScreen()); ;
                    
                }

            }
        }

        public void HandleSaveGameScreen()
        {
            if (CheckKey(Keys.Enter) || CheckButton(Buttons.A))
            {
                if (saveGame.SelectedIndex == (int)PopUpScreen.GAMESTATE.YES)
                {

                }
                else
                {
                    if (saveGame.SelectedIndex == (int)PopUpScreen.GAMESTATE.NO)
                    {
                        currentScreen.Hide();
                        currentScreen = gameMenuScreen;
                        currentScreen.Show();
                    }
                }
            }

        }


        public void HandleLoadGameScreen()
        {
            if (CheckKey(Keys.Enter) || CheckButton(Buttons.A))
            {
                if (saveGame.SelectedIndex == (int)PopUpScreen.GAMESTATE.YES)
                {

                }
                else
                {
                    if (saveGame.SelectedIndex == (int)PopUpScreen.GAMESTATE.NO)
                    {
                        currentScreen.Hide();
                        currentScreen = gameMenuScreen;
                        currentScreen.Show();
                    }
                }
            }
        }

        public void HandleAboutScreen()
        {
            if (CheckKey(Keys.Enter) || CheckButton(Buttons.A))
            {
                if (aboutScreen.SelectedIndex == (int)OtherScreen.GAMESTATE.OK)
                {
                    currentScreen.Hide();
                    currentScreen = gameMenuScreen;
                    currentScreen.Show();
                }
            }
        }

        public void HandleSettingScreen()
        {
            if (CheckKey(Keys.Enter) || CheckButton(Buttons.A))
            {
                if (saveGame.SelectedIndex == (int)PopUpScreen.GAMESTATE.YES)
                {

                }
                else
                {
                    if (saveGame.SelectedIndex == (int)PopUpScreen.GAMESTATE.NO)
                    {
                        currentScreen.Hide();
                        currentScreen = gameMenuScreen;
                        currentScreen.Show();
                    }
                }
            }
        }

        private bool CheckKey(Keys theKey)
        {
            return keyboardState.IsKeyDown(theKey) &&
                oldKeyboardState.IsKeyUp(theKey);
        }



        #endregion
    }
}
